﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using Model;
using Common;
using Model.Sys;
using System.Web.Script.Serialization;

namespace WebPortal.Controllers
{
    public class SysUserController : BaseController
    {
        #region Old
        public ActionResult UserList()
        {
            base.CheckLogin();
            return View();
        }

        /// <summary>
        /// 用户信息
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        public ActionResult Details(string id)
        {
            base.CheckLogin();
            SysUserInfo model = SysUserBLL.GetInfoById(id);
            if (model.Gender == "1")
                model.Gender = "男";
            else
                model.Gender = "女";
            return Json(model);
        }

        public ActionResult UserAdd()
        {
            base.CheckLogin();
            return View();
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model">用户信息</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(SysUserInfo model)
        {
            LoginInfo loginInfos = new LoginInfo();
            try
            {
                model.EmployeeCode = Guid.NewGuid().ToString();
                model.Guid = Guid.NewGuid().ToString();
                model.CreateTime = DateTime.Now.ToString();
                model.CreateUser = "superadmin";
                var bll = new SysUserBLL();
                bll.Insert(model);//添加用户
                new SysOperationLog(loginInfos).Log("人员管理", Request.UserHostAddress, OperationAction.添加, OperationStatus.成功,
                    "添加用户操作,操作成功", Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return RedirectToAction("UserList", RouteData.Values);
            }
            catch (Exception ex)
            {
                new SysOperationLog(loginInfos).Log("人员管理", Request.UserHostAddress, OperationAction.添加, OperationStatus.失败,
                    "添加用户操作,操作失败：" + ex.Message, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(ex.Message);
            }
        }
        /// <summary>
        /// 编辑用户页面初始化
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        public ActionResult UserEdit(string id)
        {
            base.CheckLogin();
            SysUserInfo model = new SysUserInfo();
            if (!string.IsNullOrEmpty(id))
                model = SysUserBLL.GetInfoById(id);
            else
            {
                model.Status = 1;
            }
            return View(model);
        }
        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        [HttpPost]
        public void UserUpdate(SysUserInfo model)
        {
            bool insert = false;
            if (string.IsNullOrEmpty(model.Guid))
            {
                insert = true;
                model.EmployeeCode = "MDP" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                model.Guid = Guid.NewGuid().ToString();
                model.CreateTime = DateTime.Now.ToString();
                model.CreateUser = "superadmin";
                model.UserType = 1;
            }
            var bll = new SysUserBLL();
            if (insert)//添加用户
            {
                bll.Insert(model);
                new SysOperationLog(new LoginInfo()).Log("用户管理", Request.UserHostAddress, OperationAction.添加, OperationStatus.成功,
                   "添加用户操作,操作成功,Username=" + model.Username, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
            }
            else//编辑用户
            {
                bll.Update(model);
                new SysOperationLog(new LoginInfo()).Log("用户管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                    "更新用户操作,操作成功,Username=" + model.Username, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
            }

        }
        /// <summary>
        /// 检查用户名是否存在
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public string CheckUserName(string userName)
        {
            var bll = new SysUserBLL();
            int msg = bll.CheckUserName(userName);
            if (msg == 0)
                return "存在相同的用户名!";
            else
                return "OK";
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        public int DeleteItem(string id)
        {
            SqlParameter[] paras = new SqlParameter[]
            {
                new SqlParameter("@Guid", id) 
            };
            var bll = new SysUserBLL();
            int r = bll.Delete(paras);
            if (r == 1)
                new SysOperationLog(new LoginInfo()).Log("人员管理", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功,
                        "删除用户操作,操作成功,id=" + id, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
            return r;
        }
        /// <summary>
        /// 更新用户状态
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="state">用户状态</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateState1(string id, string state)
        {
            try
            {
                var paras = new IDataParameter[4];
                paras[0] = new SqlParameter("@Guid", id);
                paras[1] = new SqlParameter("@UpdateUser", "superadmin");
                paras[2] = new SqlParameter("@UpdateTime", DateTime.Now);
                paras[3] = new SqlParameter("@State", state);
                var bll = new SysUserBLL();
                bll.UpdateState(paras);//更新状态
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        public ActionResult DeleteIF(string IFID)
        {
            try
            {
                SqlParameter[] paras = new SqlParameter[]
                {
                    new SqlParameter("@GUID", IFID) 
                };
                var bll = new SysUserBLL();
                return Json(bll.DeleteIF(paras));
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        public ActionResult UpdateFunStatus(string ID)
        {
            try
            {
                List<SqlParameter> paras = new List<SqlParameter>();
                paras.Add(new SqlParameter("@GUID", ID));
                var bll = new SysUserBLL();
                return Json(bll.UpdateFunStatus(paras));
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        #endregion

        #region List
        public ActionResult List()
        {
            return View();
        }
        public ActionResult UserIFList()
        {
            return View();
        }
        public ActionResult IFList()
        {
            return View();
        }

        public ActionResult GetUserColumnList()
        {
            LoginInfo loginInfos = base.loginInfo();
            SysUserBLL bll = new SysUserBLL();
            return Json(bll.GetUserColumnList());
        }
        public ActionResult GetIFList()
        {
            int totalCount;

            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            int pageSize = int.Parse(Request.Params["rows"]);
            int pageIndex = int.Parse(Request.Params["page"]);

            if (string.IsNullOrEmpty(sort))
            {
                sort = "CreateTime";
            }
            if (string.IsNullOrEmpty(order))
            {
                order = "asc";
            }
            LoginInfo loginInfos = base.loginInfo();
            SysUserBLL funBll = new SysUserBLL();
            var list = funBll.GetIFList(out totalCount);

            if (pageSize != 0 && pageIndex > -1 && pageSize > -1)
            {
                list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            var jsonDict = new Dictionary<String, Object> { { "total", totalCount }, { "rows", list } };
            return Json(jsonDict);
        }
        public ActionResult GetUserIFList()
        {
            string ITable = Request.Params["ITable"];
            string DBName = Request.Params["DBName"];
            int totalCount;

            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            int pageSize = int.Parse(Request.Params["rows"]);
            int pageIndex = int.Parse(Request.Params["page"]);

            if (string.IsNullOrEmpty(sort))
            {
                sort = "CreateTime";
            }
            if (string.IsNullOrEmpty(order))
            {
                order = "asc";
            }
            LoginInfo loginInfos = base.loginInfo();
            SysUserBLL funBll = new SysUserBLL();
            var list = funBll.GetUserIFList(ITable, DBName, out totalCount);

            if (pageSize != 0 && pageIndex > -1 && pageSize > -1)
            {
                list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            var jsonDict = new Dictionary<String, Object> { { "total", totalCount }, { "rows", list } };
            return Json(jsonDict);
        }
        [HttpPost]
        public ActionResult GetList()
        {
            #region 获取参数
            int totalCount = 0;

            string employeeCode = Request.Params["EmployeeCode"];
            string employeeName = Request.Params["EmployeeName"];
            string userName = Request.Params["UserName"];

            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(sort))
                sort = "EmployeeName";
            if (string.IsNullOrEmpty(order))
                sort = "desc";
            string rows = Request.Params["rows"];
            string page = Request.Params["page"];
            string expIDs = Request.Params["ExpIDs"];
            if (string.IsNullOrEmpty(expIDs))
                expIDs = "";
            #endregion

            IList<SysUserInfo> list = SysUserBLL.GetUserList(employeeCode, employeeName, userName, expIDs,
                order, sort, rows, page, out totalCount);
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", totalCount);
            jsonDict.Add("rows", list);
            return Json(jsonDict);

        }

        public ActionResult Delete(string userID)
        {
            LoginInfo loginInfos = base.loginInfo();
            //loginInfos.DBName = dbName;

            int result = 1;
            SqlParameter[] paras = new SqlParameter[]
            {
                new SqlParameter("@Guid", userID) 
            };
            var bll = new SysUserBLL();
            result = bll.Delete(paras);

            if (result == 1)
            {
                return Json(new
                {
                    Success = true,
                    Message = "删除成功"
                });
            }
            else
            {
                return Json(new
                {
                    Success = true,
                    Message = "删除失败"
                });
            }

        }

        /// <summary>
        /// 更新用户状态
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="state">用户状态</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateState(string userID)
        {

            var userInfo = SysUserBLL.GetInfoById(userID);
            if (userInfo == null)
            {
                return Json(new
                       {
                           Success = true,
                           Message = "用户不存在"
                       });
            }
            if (userInfo.Status.Equals(1))
                userInfo.Status = 2;
            else
                userInfo.Status = 1;
            try
            {
                var paras = new IDataParameter[4];
                paras[0] = new SqlParameter("@Guid", userInfo.Guid);
                paras[1] = new SqlParameter("@UpdateUser", "superadmin");
                paras[2] = new SqlParameter("@UpdateTime", DateTime.Now);
                paras[3] = new SqlParameter("@State", userInfo.Status);
                var bll = new SysUserBLL();
                bll.UpdateState(paras);//更新状态
                //return RedirectToAction("Index");
                string message = string.Format("成功将用户 {0}({1}) 的状态更改为 {2}",
                    userInfo.EmployeeName, userInfo.Username,
                    userInfo.Status.Equals(1) ? "启用" : "禁用");
                return Json(new
                {
                    Success = true,
                    Message = message
                });
            }
            catch (Exception ex)
            {
                string message = string.Format("更改用户 {0}({1}) 的状态时出现错误",
                    userInfo.EmployeeName, userInfo.Username,
                    ex.Message);
                return Json(new
                {
                    Success = false,
                    Message = message
                });
            }

        }
        #endregion

        #region Edit

        public ActionResult SaveUserIF()
        {
            SysUserBLL bll = new SysUserBLL();

            string query = Request.Params["query"];
            string queryExt = Request.Params["queryExt"];
            string modelID = Request.Params["modelID"];
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            List<UserIFConfig> modelList = (List<UserIFConfig>)jsSerializer.Deserialize(query, typeof(List<UserIFConfig>));
            List<UserIFConfig> modelExtList = (List<UserIFConfig>)jsSerializer.Deserialize(queryExt, typeof(List<UserIFConfig>));
            for (int i = 0; i < modelExtList.Count; i++)
            {
                UserIFConfig extModel = modelExtList[i];
                extModel.UserColumnName = string.Format("COL{0}", i + 1);
                modelList.Add(extModel);
            }
            try
            {
                return Json(bll.UpdateUserIF(modelList, modelID));
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        public ActionResult SaveIFItem()
        {
            SysUserBLL bll = new SysUserBLL();
            #region 更新数据
            string query = Request.Params["query"];
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            IFConfig model = (IFConfig)jsSerializer.Deserialize(query, typeof(IFConfig));

            var taskResult = 0;
            if (string.IsNullOrEmpty(model.GUID))
            {
                model.GUID = Guid.NewGuid().ToString();
                taskResult = bll.InsertIF(model);
            }
            else
            {
                taskResult = bll.UpdateIF(model);
            }

            #endregion

            return Json(taskResult);
        }
        public ActionResult EditIF(string IFID)
        {
            IFConfig IFInfo = new IFConfig();
            if (!string.IsNullOrEmpty(IFID))
            {
                IFInfo = SysUserBLL.GetIFInfoById(IFID);
            }
            return View(IFInfo);
        }
        public ActionResult EditUserIF()
        {
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            string modelID = "";
            List<SysConfig> rows = bll.GetSysConfig("2");
            if (rows.Count > 0)
                modelID = rows[0].KeyValue;
            ModelConfigBLL mbll = new ModelConfigBLL(loginInfos);
            ModelConfig model = mbll.GetItem(modelID);
            return View(model);
        }
        public ActionResult Edit(string userID)
        {
            SysUserInfo userInfo = new SysUserInfo();
            userInfo.Status = 1;
            if (!string.IsNullOrEmpty(userID))
            {
                userInfo = SysUserBLL.GetInfoById(userID);
            }
            return View(userInfo);
        }
        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        public ActionResult Update(SysUserInfo model, FormCollection form)
        { 
            LoginInfo loginInfos = base.loginInfo();
            SysUserBLL userBll = new SysUserBLL();
             
            #region 参数检查
            if (string.IsNullOrEmpty(model.Guid) && string.IsNullOrEmpty(model.Username))
            {
                return Json("用户名不能为空！");
            }
            if (string.IsNullOrEmpty(model.EmployeeName))
            {
                return Json("姓名不能为空！");
            } 
            #endregion

            #region 更新数据
            try
            {
                var taskResult = 1;
                if (string.IsNullOrEmpty(model.Guid))//新建用户
                {
                    model.EmployeeCode = "MDP" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    model.Guid = Guid.NewGuid().ToString();
                    model.CreateTime = DateTime.Now.ToString();
                    model.CreateUser = "superadmin";
                    model.UserType = 1;

                    var samelist = userBll.GetByUsernameWithOutId(model.Username);
                    if (samelist.Count > 0)
                    {
                        return Json("保存失败,存在相同的用户名");
                    }
                    taskResult = userBll.Insert(model);
                }
                else//编辑用户
                {
                    if (string.IsNullOrEmpty(model.EmployeeCode))
                    {
                        model.EmployeeCode = "MDP" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    }
                    var samelist = userBll.GetByUsernameWithOutId(model.Username, model.Guid);
                    if (samelist.Count > 0)
                    {
                        return Json(2);
                    }
                    taskResult = userBll.Update(model);
                }
                return Json(1);
            #endregion
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        #endregion

        #region Read
        public ActionResult Read(string userID)
        {
            SysUserInfo userInfo = null;
            if (!string.IsNullOrEmpty(userID))
            {
                userInfo = SysUserBLL.GetInfoById(userID);
            }
            if (userInfo == null)
            {
                userInfo = new SysUserInfo();
                userInfo.Status = 1;
            }
            return View(userInfo);
        }

        #endregion
    }
}